package controller

import (
	"fmt"
	"net/http"
	"time"

	"github.com/260444/ginEssential/common"
	"github.com/260444/ginEssential/model"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type IAirportController interface {
	RestController
}

type AirportController struct {
	db *gorm.DB
}

func NewAirportController() IAirportController {
	db := common.GetDB()
	db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='机场信息'").AutoMigrate(&model.Airport{})
	return AirportController{db}
}
func (a AirportController) AddAirport(ctx *gin.Context) {
	var airport model.Airport
	err := ctx.Bind(&airport)
	airport.CDATE = time.Now()
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "请求参数错误",
		})
		return
	}

	result := a.db.Where("ap3c = ?", airport.AP3C).First(&airport)
	if result.RowsAffected > 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "机场已存在",
		})
		return
	}

	result = a.db.Create(&airport)
	if result.Error != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  fmt.Sprintf("成功添加信息，数量:%d条", result.RowsAffected),
	})

	fmt.Println(time.Now())
}

func (a AirportController) DelAirport(ctx *gin.Context) {
	var airport model.Airport
	ctx.Bind(&airport)
	fmt.Println(airport.AP3C)
	result := a.db.Where("AP3C = ?", airport.AP3C).Delete(&airport)
	if result.Error != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func (a AirportController) PutAirport(ctx *gin.Context) {
	var query model.Airport
	var body model.Airport
	ctx.BindQuery(query)
	ctx.ShouldBindBodyWithJSON(body)
	a.db.Where("AP3C = ?", query.AP3C).First(&query)
	query.AP3C = body.AP3C
	query.AP4C = body.AP4C
	a.db.Save(&query)
}

func (a AirportController) GetAirport(ctx *gin.Context) {
	var airports []model.Airport
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{"user": airports},
	})
}
